import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { message } from 'antd'
import { useNavigate } from 'react-router-dom'
class Request {
    private instance: AxiosInstance
    private readonly config: AxiosRequestConfig
    private static messageApi = message
    // private navigate = useNavigate()

    constructor(config: AxiosRequestConfig) {
        this.config = config
        this.instance = axios.create(this.config)

        // 请求拦截器
        this.instance.interceptors.request.use(
            (config) => {
                // 在这里添加 token 等全局请求头
                const token = localStorage.getItem('token')
                if (token) {
                    config.headers.Authorization = `${token}`
                }
                return config
            },
            (error) => Promise.reject(error)
        )

        // 响应拦截器
        this.instance.interceptors.response.use(
            (response: AxiosResponse) => {
                if (response.data.code != 200) Request.messageApi.error(response.data.msg) 
                return response.data // 直接返回后端数据（包括 msg, data, code）
            },
            (error) => {
                if (error.response) {
                    const { status } = error.response
                    switch (status) {
                        case 401:
                            Request.messageApi.error('未授权，请重新登录')
                            break
                        case 403:
                            Request.messageApi.error('拒绝访问')
                            break
                        case 500:
                            Request.messageApi.error('服务器错误')
                            break
                        case 504:
                            Request.messageApi.error('服务端未启动，请联系管理员！')
                            break
                        default:
                            Request.messageApi.error(`请求错误: ${status}`)
                    }
                }
                return Promise.reject(error)
            }
        )
    }

    public async setMessageApi(messageInstance: any) {
        Request.messageApi = messageInstance
    }

    public async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.get(url, config)
    }

    public async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.post(url, data, config)
    }

    public async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.put(url, data, config)
    }

    public async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.delete(url, config)
    }
}

// 创建默认请求实例
const request = new Request({
    baseURL: '/dev_api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

export default request
